<template>
  <div class="container">
    <el-card class="search-container">
      <el-form
        :model="searchForm"
        size="mini"
        :inline="true"
        label-suffix="："
        ref="searchForm"
      >
        <el-form-item label="订单ID" prop="order_id">
          <el-input v-model="searchForm.order_id" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="body">
          <el-input v-model="searchForm.body" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="searchForm.status" clearable placeholder="请选择">
            <el-option
              v-for="(item, index) in statusList"
              :key="`status_${index}`"
              :label="item"
              :value="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="商品类型" prop="type">
          <el-select v-model="searchForm.type" clearable placeholder="请选择">
            <el-option
              v-for="(item, index) in typeList"
              :key="`type_${index}`"
              :label="item"
              :value="index"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="searchHandle">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="container-result">
      <thy-caption title="查询结果" margin />
      <el-table stripe border :data="list" v-loading="loading">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-form class="demo-table-expand" label-suffix="：" label-width="100px">
              <el-form-item label="订单 ID">
                <span>{{ scope.row.order_id }} </span>
              </el-form-item>
              <el-form-item label="订单金额">
                <span>￥{{ scope.row.total_fee / 100 }} </span>
              </el-form-item>
              <el-form-item label="商品名称">
                <span
                  >{{
                    `${scope.row.body}（${typeList[scope.row.detail.type] ||
                      '邮寄'}）`
                  }}
                </span>
              </el-form-item>

              <el-form-item label="订单数量">
                <span>{{ scope.row.detail.count }}</span>
              </el-form-item>
              <el-form-item label="订单详情">
                <template v-if="scope.row.detail.form">
                  <el-tag
                    v-for="(value, key) in scope.row.detail.form"
                    :key="`form_detail_${key}`"
                    effect="dark"
                  >
                    <template v-if="key === 'sex'">
                      {{ `${dict[key]}: ${value ? '男' : '女'}` }}
                    </template>
                    <template v-else>
                      {{ `${dict[key]}: ${value || '无'}` }}
                    </template>
                  </el-tag>
                </template>
                <template v-else-if="scope.row.detail.property">
                  <el-tag
                    v-for="(item, index) in scope.row.detail.property"
                    :key="`tag_${index}`"
                  >
                    {{ `${item.name}：${item.label}` }}
                  </el-tag>
                </template>
              </el-form-item>
              <el-form-item label="收货地址">
                <span v-if="scope.row.detail.address">{{
                  `${scope.row.detail.address.provinceStr}${scope.row.detail.address.cityStr}${scope.row.detail.address.cityStr}${scope.row.detail.address.address}_${scope.row.detail.address.code}_${scope.row.detail.address.linkMan}_${scope.row.detail.address.mobile}`
                }}</span>
                <span v-else>-</span>
              </el-form-item>
              <el-form-item label="订单备注">
                <template
                  v-if="scope.row.remark"
                  v-for="(value, key) in scope.row.remark"
                >
                  <template v-if="typeof value === 'object'">
                    <span :key="`form_remark_${key}`">{{
                      JSON.stringify(value)
                    }}</span>
                  </template>
                  <el-tag v-else :key="`form_remark_${key}`" effect="dark">
                    <template v-if="key === 'sex'">
                      {{ `${dict[key]}: ${value ? '男' : '女'}` }}
                    </template>
                    <template v-else-if="key === 'subType'">
                      {{ `${dict[key]}: ${value ? '晚餐' : '午餐'}` }}
                    </template>
                    <template v-else-if="key === 'subTime'">
                      {{ `${dict[key]}: ${formatDate(value)}` }}
                    </template>
                    <template v-else>
                      {{ `${dict[key]}: ${value || '无'}` }}
                    </template>
                  </el-tag>
                </template>
                <span v-else>-</span>
              </el-form-item>
              <el-form-item label="用户 ID">
                <span>{{ scope.row.user_id }}</span>
              </el-form-item>
              <el-form-item label="创建日期">
                <span>{{ formatDate(scope.row.created_at) }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="序号" width="60" align="center" />
        <el-table-column prop="order_id" label="订单ID" />
        <el-table-column prop="total_fee" label="总金额(￥)" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.total_fee / 100 }} </span>
          </template>
        </el-table-column>
        <el-table-column label="商品名称">
          <template slot-scope="scope">
            <span
              >{{
                `${scope.row.body}（${typeList[scope.row.detail.type] ||
                  '邮寄'}）`
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="商品图片" width="120" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.goods_info.pic" alt="" width="100" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="订单详情" width="240" align="center">
          <template slot-scope="scope">
            <el-tag>数量：{{ scope.row.detail.count }}</el-tag>
            <template v-if="scope.row.detail.form">
              <el-tag
                v-for="(value, key) in scope.row.detail.form"
                :key="`form_detail_${key}`"
                effect="dark"
              >
                <template v-if="key === 'sex'">
                  {{ `${dict[key]}: ${value ? '男' : '女'}` }}
                </template>
                <template v-else>
                  {{ `${dict[key]}: ${value || '无'}` }}
                </template>
              </el-tag>
            </template>
            <template v-else-if="scope.row.detail.property">
              <el-tag
                v-for="(item, index) in scope.row.detail.property"
                :key="`tag_${index}`"
              >
                {{ `${item.name}：${item.label}` }}
              </el-tag>
            </template>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="收货地址" width="260" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.detail.address">
              <span>{{
                `${scope.row.detail.address.provinceStr}${scope.row.detail.address.cityStr}${scope.row.detail.address.cityStr}${scope.row.detail.address.address}_${scope.row.detail.address.code}_${scope.row.detail.address.linkMan}_${scope.row.detail.address.mobile}`
              }}</span>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column> -->
        <el-table-column
          label="订单状态"
          fixed="right"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.status === 1" style="color: red;">
              已取消
            </span>
            <span
              v-else-if="scope.row.status === 2 && scope.row.detail.type === 0"
              style="color: blue;"
            >
              待发货
            </span>
            <span
              v-else-if="scope.row.status === 2 && scope.row.detail.type === 1"
              style="color: blue;"
            >
              待预约
            </span>
            <span
              v-else-if="scope.row.status === 3 && scope.row.detail.type === 0"
              style="color: green;"
            >
              已发货
            </span>
            <span
              v-else-if="scope.row.status === 3 && scope.row.detail.type === 1"
            >
              待确认预约
            </span>
            <span v-else-if="scope.row.status === 4" style="color: green;">
              预约成功
            </span>
            <span v-else-if="scope.row.status === 5" style="color: red;">
              预约失败
            </span>
            <span v-else>
              待支付
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="订单备注" width="220" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.remark">
              <template v-for="(value, key) in scope.row.remark">
                <template v-if="typeof value === 'object'">
                  <span :key="`form_remark_${key}`">{{
                    JSON.stringify(value)
                  }}</span>
                </template>
                <el-tag v-else :key="`form_remark_${key}`" effect="dark">
                  <template v-if="key === 'sex'">
                    {{ `${dict[key]}: ${value ? '男' : '女'}` }}
                  </template>
                  <template v-else-if="key === 'subType'">
                    {{ `${dict[key]}: ${value ? '晚餐' : '午餐'}` }}
                  </template>
                  <template v-else-if="key === 'subTime'">
                    {{ `${dict[key]}: ${formatDate(value)}` }}
                  </template>
                  <template v-else>
                    {{ `${dict[key]}: ${value || '无'}` }}
                  </template>
                </el-tag>
              </template>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="user_id" label="用户ID" width="240" /> -->
        <!-- <el-table-column prop="created_at" label="创建日期" width="180">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.created_at) }}</span>
          </template>
        </el-table-column> -->
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.status === 2">
              <el-button
                v-if="scope.row.detail.type === 2"
                type="text"
                size="small"
                @click="actionHandle(scope.$index, 2)"
                >下发
              </el-button>
              <el-button
                v-else-if="
                  scope.row.detail.type > 2 || scope.row.detail.type === 0
                "
                type="text"
                size="small"
                @click="actionHandle(scope.$index, 3)"
                >发货
              </el-button>
            </template>
            <template v-else-if="scope.row.status === 3">
              <el-button
                v-if="scope.row.detail.type === 1"
                type="text"
                size="small"
                @click="actionHandle(scope.$index, 1)"
                >预约
              </el-button>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        @current-change="paginationHandle"
        :current-page="page"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog title="订单操作" :visible.sync="dialogVisible">
      <el-form
        v-if="dialogVisible"
        :model="form"
        label-width="120px"
        label-suffix="："
        size="mini"
        ref="form"
      >
        <template v-if="type === 1">
          <el-form-item label="预约状态" prop="appointment" required>
            <el-select v-model="form.appointment">
              <el-option label="成功" :value="4" />
              <el-option label="失败" :value="10000" />
            </el-select>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="快递公司" prop="type" required>
            <el-select v-model="form.type">
              <el-option
                v-for="item in kuaidiList"
                :key="`kuaidi_${item.value}`"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="快递单号" prop="postid" required>
            <el-input placeholder="请输入" v-model="form.postid" />
          </el-form-item>
          <el-form-item label="收货人手机号" prop="phone" required>
            <el-input placeholder="请输入" v-model="form.phone" />
          </el-form-item>
        </template>
        <el-form-item>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitHandle">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { format } from 'date-fns';
import randomColor from 'randomcolor';
import deepClean from 'deep-clean';
export default {
  name: 'flash-order',
  data() {
    return {
      loading: false,
      searchForm: {},
      list: [],
      total: 0,
      page: 1,
      form: {},
      dialogVisible: false,
      type: null,
      typeList: ['邮寄', '人工预约', '券码'],
      statusList: ['待支付', '已取消', '待发货', '已发货'],
      statusList2: [
        '待支付',
        '已取消',
        '待预约',
        '已预约',
        '预约成功',
        '预约失败'
      ],
      kuaidiList: [
        {
          label: '圆通',
          value: 'yuantong'
        },
        {
          label: '顺丰',
          value: 'shunfeng'
        },
        {
          label: 'EMS',
          value: 'ems'
        },
        {
          label: '邮政国内',
          value: 'youzhengguonei'
        },
        {
          label: '百世汇通',
          value: 'huitongkuaidi'
        },
        {
          label: '申通',
          value: 'shentong'
        },
        {
          label: '中通',
          value: 'zhongtong'
        },
        {
          label: '国通',
          value: 'guotongkuaidi'
        },
        {
          label: '韵达',
          value: 'yunda'
        },
        {
          label: '天天',
          value: 'tiantian'
        },
        {
          label: '京东',
          value: 'jd'
        }
      ],
      dict: {
        username: '姓名',
        phone: '手机',
        age: '年龄',
        sex: '性别',
        remark: '备注',
        subTime: '预约时间',
        logistics: '快递信息',
        count: '数量',
        subType: '消费类型'
      }
    };
  },
  methods: {
    formatDate(date) {
      return format(date, 'YYYY-MM-DD HH:mm:ss');
    },
    colorHandle() {
      return randomColor({ luminosity: 'dark' });
    },
    searchHandle() {
      this.$refs.searchForm.validate(valid => {
        if (valid) {
          this.getData();
        }
      });
    },
    getData(page = 1) {
      this.loading = true;
      this.$request
        .get('/admin/flash/order/list', {
          params: deepClean({
            page,
            pageSize: 10,
            ...this.searchForm
          })
        })
        .then(data => {
          this.page = page;
          this.list = data.rows.map(item => {
            const { detail, remark, ...others } = item;
            return {
              ...others,
              detail: JSON.parse(detail),
              remark: JSON.parse(remark || '{}')
            };
          });
          this.total = data.count;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    paginationHandle(page) {
      this.getData(page);
    },
    actionHandle(idx, type) {
      this.form = JSON.parse(JSON.stringify(this.list[idx]));
      this.type = type;
      switch (type) {
        case 1:
          this.dialogVisible = true;
          break;
        case 2:
          this.dialogVisible = true;
          break;
        default:
          this.form.phone = this.form.detail.address.mobile.slice(-4);
          this.dialogVisible = true;
          break;
      }
    },
    submitHandle() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const {
            order_id,
            type,
            postid,
            phone,
            appointment,
            detail
          } = this.form;
          if (this.type === 1) {
            const remark = this.form.remark;
            remark.phone = detail.form.phone;
            this.orderUpdate({
              id: order_id,
              status: appointment,
              remark
            });
          } else {
            // 邮寄
            const label = this.kuaidiList.find(item => item.value === type)
              .label;
            const remark = {
              logistics: {
                type,
                label,
                postid,
                phone
              }
            };
            this.orderUpdate({
              id: order_id,
              status: 3,
              remark
            });
          }
        }
      });
    },
    orderUpdate(params) {
      return this.$request
        .post('/admin/flash/order/update', params)
        .then(() => {
          this.$message.success('更新订单成功');
          this.dialogVisible = false;
          this.getData(this.page);
        });
    },
    getGoodsList() {
      return this.$request.get('/admin/flash/goods/list').then(data => {
        this.goodsList = data.filter(item => item.type === 2);
      });
    }
  },
  mounted() {
    this.getData();
  }
};
</script>

<style>
</style>
